from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN
from io import BytesIO
import json
from typing import List
from datetime import datetime

app = FastAPI()

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 定义配色方案
COLORS = {
    'primary_blue': RGBColor(23, 82, 120),
    'primary_gold': RGBColor(220, 160, 70),
    'white': RGBColor(255, 255, 255),
    'dark_gray': RGBColor(30, 30, 30),
    'light_gray': RGBColor(248, 249, 250)
}

@app.post("/generate")
async def generate_ppt(
    title: str = Form(...),
    subtitle: str = Form(""),
    company: str = Form(""),
    news_points: str = Form("[]"),
    logo: UploadFile = File(None)
):
    try:
        # 解析新闻要点
        news_points_list = json.loads(news_points)
        
        # 创建PPT
        prs = Presentation()
        
        # 1. 封面页
        slide_layout = prs.slide_layouts[0]  # 标题幻灯片
        slide = prs.slides.add_slide(slide_layout)
        
        # 设置背景色
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = COLORS['dark_gray']
        
        # 设置标题
        title_shape = slide.shapes.title
        title_frame = title_shape.text_frame
        title_frame.text = title
        title_frame.paragraphs[0].font.size = Pt(48)
        title_frame.paragraphs[0].font.color.rgb = COLORS['white']
        title_frame.paragraphs[0].font.name = '微软雅黑'
        title_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
        
        # 设置副标题
        subtitle_shape = slide.placeholders[1]
        subtitle_frame = subtitle_shape.text_frame
        subtitle_frame.text = subtitle or "专业媒体传播解决方案"
        subtitle_frame.paragraphs[0].font.size = Pt(24)
        subtitle_frame.paragraphs[0].font.color.rgb = COLORS['primary_gold']
        subtitle_frame.paragraphs[0].font.name = '微软雅黑'
        subtitle_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
        
        # 2. 目录页
        slide_layout = prs.slide_layouts[1]  # 标题和内容
        slide = prs.slides.add_slide(slide_layout)
        
        # 设置背景色
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = COLORS['light_gray']
        
        # 设置标题
        title_shape = slide.shapes.title
        title_frame = title_shape.text_frame
        title_frame.text = "方案目录"
        title_frame.paragraphs[0].font.size = Pt(36)
        title_frame.paragraphs[0].font.color.rgb = COLORS['primary_blue']
        title_frame.paragraphs[0].font.name = '微软雅黑'
        
        # 设置内容
        content_shape = slide.placeholders[1]
        content_frame = content_shape.text_frame
        content_frame.text = "1. 项目背景与目标"
        
        p = content_frame.add_paragraph()
        p.text = "2. 媒体策略与执行"
        p.level = 0
        
        p = content_frame.add_paragraph()
        p.text = "3. 传播渠道与资源"
        p.level = 0
        
        p = content_frame.add_paragraph()
        p.text = "4. 效果评估与优化"
        p.level = 0
        
        p = content_frame.add_paragraph()
        p.text = "5. 预算与时间规划"
        p.level = 0
        
        # 设置字体样式
        for paragraph in content_frame.paragraphs:
            paragraph.font.size = Pt(20)
            paragraph.font.color.rgb = COLORS['dark_gray']
            paragraph.font.name = '微软雅黑'
        
        # 3. 新闻要点页
        if news_points_list:
            slide_layout = prs.slide_layouts[1]  # 标题和内容
            slide = prs.slides.add_slide(slide_layout)
            
            # 设置背景色
            background = slide.background
            fill = background.fill
            fill.solid()
            fill.fore_color.rgb = COLORS['white']
            
            # 设置标题
            title_shape = slide.shapes.title
            title_frame = title_shape.text_frame
            title_frame.text = "核心新闻要点"
            title_frame.paragraphs[0].font.size = Pt(36)
            title_frame.paragraphs[0].font.color.rgb = COLORS['primary_blue']
            title_frame.paragraphs[0].font.name = '微软雅黑'
            
            # 设置内容
            content_shape = slide.placeholders[1]
            content_frame = content_shape.text_frame
            content_frame.text = ""
            
            for i, point in enumerate(news_points_list, 1):
                if i == 1:
                    content_frame.paragraphs[0].text = f"• {point}"
                else:
                    p = content_frame.add_paragraph()
                    p.text = f"• {point}"
                
                paragraph = content_frame.paragraphs[i-1]
                paragraph.font.size = Pt(18)
                paragraph.font.color.rgb = COLORS['dark_gray']
                paragraph.font.name = '微软雅黑'
        
        # 4. 结束页
        slide_layout = prs.slide_layouts[2]  # 空白幻灯片
        slide = prs.slides.add_slide(slide_layout)
        
        # 设置背景色
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = COLORS['primary_blue']
        
        # 添加结束语
        left = Inches(1)
        top = Inches(2.5)
        width = Inches(8)
        height = Inches(2)
        
        textbox = slide.shapes.add_textbox(left, top, width, height)
        text_frame = textbox.text_frame
        text_frame.text = "谢谢观看"
        text_frame.paragraphs[0].font.size = Pt(48)
        text_frame.paragraphs[0].font.color.rgb = COLORS['white']
        text_frame.paragraphs[0].font.name = '微软雅黑'
        text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
        
        # 添加公司信息
        if company:
            left = Inches(1)
            top = Inches(4.5)
            width = Inches(8)
            height = Inches(1)
            
            textbox = slide.shapes.add_textbox(left, top, width, height)
            text_frame = textbox.text_frame
            text_frame.text = company
            text_frame.paragraphs[0].font.size = Pt(24)
            text_frame.paragraphs[0].font.color.rgb = COLORS['primary_gold']
            text_frame.paragraphs[0].font.name = '微软雅黑'
            text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
        
        # 保存到内存
        buffer = BytesIO()
        prs.save(buffer)
        buffer.seek(0)
        
        # 返回文件
        filename = f"{title}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pptx"
        
        return StreamingResponse(
            buffer,
            media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
            headers={"Content-Disposition": f"attachment; filename={filename}"}
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def root():
    return {"message": "高端新闻曝光服务方案PPT生成器API"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)